/*
 * Copyright (C) 2009 AnK Team
 *	 Andrey Korolev
 *	 Anna Krel
 *	 Anna Kapanina
 *	 
 *	 http://code.google.com/p/ankfood/	
 *    
     
 *    Licensed under the GNU General Public License, Version 2.0 (the "License");
 *
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *         http://www.gnu.org/licenses/gpl-2.0.html

 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,

 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */



package org.ank.food;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class ProductInfoActivity extends Activity{ 
	
	public static final String INTENT_EXTRA_NAME_PROD_ID = "prinfo1";
	public static final String INTENT_EXTRA_NAME_MODE = "prinfo2";
	public static final String INTENT_EXTRA_NAME_ITEM_ID = "prinfo3";
	public static final int MODE_ADD_NEW_ITEM = 0;
	public static final int MODE_EDIT_ITEM = 1;
	public static final int MAX_AMOUNT = 99;
	public static final int MAX_GROUP_NAME_LENGTH = 9;
	
	private Button addButton, backButton, picturesButton;
	private ImageButton plusButton, minusButton;
	private int amount, prodId, curProtEnergy, curCarboEnergy, curFatEnergy, 
				curEnergy, weight, weightItemId, mode, menuItemId;
	private Spinner weightSpinner;
	private /*SimpleCursorAdapter*/ServingAdapter adapter;
	private	TextView title, /*per100gProt, per100gFat, per100gCarbo, per100gEnergy,*/ perAmountTitle,
					perAmountProt, perAmountFat, perAmountCarbo, perAmountEnergy, noInfoView
					/*,addToMenuTitle*/;
	private View amountLayout/*, perAmountLayout*/;
	private EditText amountEditText;
	private boolean amountIsOk = false;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_info_activity);
        
        Intent parentIntent = getIntent();
        if ( (mode = parentIntent.getIntExtra(INTENT_EXTRA_NAME_MODE, MODE_ADD_NEW_ITEM))
        		== MODE_EDIT_ITEM )
        	setTitle(getString(R.string.app_name)+" - "+getString(R.string.edit_menu));
        else        	
        	setTitle(getString(R.string.app_name)+" - "+getString(R.string.add_product_to_menu));
        
        
        title = (TextView)findViewById(R.id.product_info_product_name);
//        per100g = (TextView)findViewById(R.id.product_info_per_100g);
        
        addButton = (Button)findViewById(R.id.product_info_add_button);
        backButton = (Button)findViewById(R.id.product_info_back_button);
        plusButton = (ImageButton)findViewById(R.id.product_info_plus_button);
        picturesButton = (Button)findViewById(R.id.product_info_pictures_button);
        minusButton = (ImageButton)findViewById(R.id.product_info_minus_button);
        amountEditText = (EditText)findViewById(R.id.product_info_amount);
        weightSpinner = (Spinner)findViewById(R.id.product_info_unit);
//        per100gProt = (TextView)findViewById(R.id.product_info_per100g_prot_value);
//        per100gFat = (TextView)findViewById(R.id.product_info_per100g_fat_value);
//        per100gCarbo = (TextView)findViewById(R.id.product_info_per100g_carbo_value);
//        per100gEnergy = (TextView)findViewById(R.id.product_info_per100g_energy_value);
        perAmountTitle = (TextView)findViewById(R.id.product_info_per_amount_title);
        perAmountProt = (TextView)findViewById(R.id.product_info_per_amount_prot_value);
        perAmountFat = (TextView)findViewById(R.id.product_info_per_amount_fat_value);
        perAmountCarbo = (TextView)findViewById(R.id.product_info_per_amount_carbo_value);
        perAmountEnergy = (TextView)findViewById(R.id.product_info_per_amount_energy_value);
        noInfoView = (TextView)findViewById(R.id.product_info_no_info);
        amountLayout = findViewById(R.id.product_info_amount_layout);
//        perAmountLayout = findViewById(R.id.product_info_per_amount_layout);
//        addToMenuTitle = (TextView)findViewById(R.id.product_info_add_to_menu);
        
        
        if ( mode == MODE_EDIT_ITEM){
        	menuItemId = parentIntent.getIntExtra(INTENT_EXTRA_NAME_ITEM_ID, 0);
        	prodId = MenuManager.getInstance(getApplicationContext()).
        			getMenuItemProductId(menuItemId);
        	title.setText( MenuManager.getInstance(getApplicationContext()).
            		getMenuItemProductName(menuItemId));
        }else{
        	prodId = parentIntent.getIntExtra(INTENT_EXTRA_NAME_PROD_ID, 0);
        	title.setText( ProductDataManager.getInstance(getApplicationContext()).
            		getProductNameById(prodId) );
        }
                
        
        
//        StringBuffer buf = new StringBuffer();
//        buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductProtValue(prodId))
//        .append(' ').append(getString(R.string.g)).append(" (")
//        .append(ProductDataManager.getInstance(getApplicationContext()).getProductProtEnergy(prodId))
//        .append(' ').append(getString(R.string.kcal)).append(')');
//        per100gProt.setText(buf.toString());
//        
//        buf = new StringBuffer();
//        buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductFatValue(prodId))
//        .append(' ').append(getString(R.string.g)).append(" (")
//        .append(ProductDataManager.getInstance(getApplicationContext()).getProductFatEnergy(prodId))
//        .append(' ').append(getString(R.string.kcal)).append(')');
//        per100gFat.setText(buf.toString());
//        
//        buf = new StringBuffer();
//        
//        buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductCarboValue(prodId))
//        .append(' ').append(getString(R.string.g)).append(" (")
//        .append(ProductDataManager.getInstance(getApplicationContext()).getProductCarboEnergy(prodId))
//        .append(' ').append(getString(R.string.kcal)).append(')');
//        per100gCarbo.setText(buf.toString());
//        
//        buf = new StringBuffer();
//        buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductEnergyValue(prodId))
//        .append(' ').append(getString(R.string.kcal));
//        per100gEnergy.setText(buf.toString());
        
        backButton.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View v){
        		setResult(RESULT_CANCELED);
        		finish();
        	}
        });
        StringBuffer titleBuf = new StringBuffer(ProductDataManager.getInstance(getApplicationContext()).
        		getSubgroupNameOfProduct(prodId));
        if(titleBuf.length() > MAX_GROUP_NAME_LENGTH){
        	titleBuf.delete(MAX_GROUP_NAME_LENGTH-3, titleBuf.length());
        	titleBuf.append("...");
        }
        backButton.setText(titleBuf.toString());

        Cursor weightCursor;
        //if we have no info about weight items for this product, adding is not allowed
        if ( 	( weightCursor = 
        			ProductDataManager.getInstance(getApplicationContext()).
        				getWeightItemsForProduct(prodId)
        		).getCount() == 0  ){
        	//set values per 100g
        	
        	perAmountTitle.setText(getString(R.string.per_100g));
        	
        	StringBuffer buf = new StringBuffer();
            buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductProtValue(prodId))
            .append(' ').append(getString(R.string.g)).append(" (")
            .append(ProductDataManager.getInstance(getApplicationContext()).getProductProtEnergy(prodId))
            .append(' ').append(getString(R.string.kcal)).append(')');
            perAmountProt.setText(buf.toString());
            
            buf = new StringBuffer();
            buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductFatValue(prodId))
            .append(' ').append(getString(R.string.g)).append(" (")
            .append(ProductDataManager.getInstance(getApplicationContext()).getProductFatEnergy(prodId))
            .append(' ').append(getString(R.string.kcal)).append(')');
            perAmountFat.setText(buf.toString());
            
            buf = new StringBuffer();            
            buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductCarboValue(prodId))
            .append(' ').append(getString(R.string.g)).append(" (")
            .append(ProductDataManager.getInstance(getApplicationContext()).getProductCarboEnergy(prodId))
            .append(' ').append(getString(R.string.kcal)).append(')');
            perAmountCarbo.setText(buf.toString());
            
            buf = new StringBuffer();
            buf.append(ProductDataManager.getInstance(getApplicationContext()).getProductEnergyValue(prodId))
            .append(' ').append(getString(R.string.kcal));
            perAmountEnergy.setText(buf.toString());
            
//        	addToMenuTitle.setVisibility(View.GONE);
        	amountLayout.setVisibility(View.GONE);
        	addButton.setVisibility(View.GONE);
        	noInfoView.setVisibility(View.VISIBLE);
        	weightCursor.close();
        	return;
        }
        
        adapter = new ServingAdapter( getApplicationContext(),
        		android.R.layout.simple_spinner_item,
        		weightCursor,  
        		new String[]{
        			ProductDataProvider.COLUMN_NAMES_WEIGHT[ProductDataProvider.WEIGHT_NAME]
        		},
    			new int[] {android.R.id.text1} );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        weightSpinner.setAdapter(adapter);
        weightSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				checkAmount();
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
        	
        });
        if ( mode == MODE_EDIT_ITEM ){
        	amountEditText.setText(String.valueOf(
        			MenuManager.getInstance(getApplicationContext()).
            			getMenuItemAmount(menuItemId)	)
            		);
        	int curWeightItemId = MenuManager.getInstance(getApplicationContext()).
        			getMenuItemWeightId(menuItemId);
        	int pos;
        	for(pos = 0; pos < weightCursor.getCount(); pos++){
        		weightCursor.moveToPosition(pos);
        		if(weightCursor.getInt(0) == curWeightItemId)
        			break;
        	}
        	weightSpinner.setSelection(pos);
        	addButton.setText(R.string.save);
        	backButton.setText(R.string.my_menu);
//        	addToMenuTitle.setText(R.string.edit_menu_entry);
        }
        checkAmount();
        amountEditText.setOnKeyListener(new EditText.OnKeyListener(){
			public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
				checkAmount();
				return false;
			}
        });
        plusButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View arg0) {
				int cur;
				String s = amountEditText.getText().toString();
				if (TextUtils.isEmpty(s))
					cur = 0;
				else
					cur = Integer.parseInt(s);
				if (cur < MAX_AMOUNT)
					amountEditText.setText(String.valueOf( cur+1 ));
				checkAmount();
			}
        });
        minusButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View arg0) {
				int cur;
				String s = amountEditText.getText().toString();
				if (TextUtils.isEmpty(s) || (cur = Integer.parseInt(s)) == 0 ||
						(cur = Integer.parseInt(s)) == 1)
					amountEditText.setText(String.valueOf( 1 ));
				else
					amountEditText.setText(String.valueOf( cur-1 ));
				checkAmount();
			}
        });
        
        addButton.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View v){
        		if (amountIsOk){
        			if ( mode == MODE_EDIT_ITEM )
        				MenuManager.getInstance(getApplicationContext()).
        						updateMenuItem(menuItemId,weightItemId,amount);
        			else
        				MenuManager.getInstance(getApplicationContext()).
								saveNewMenuItem(prodId,weightItemId,amount);
        			setResult(RESULT_OK);
        			finish();
        		}else{
        			AlertDialog.Builder builder = new AlertDialog.Builder(ProductInfoActivity.this);
        			builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.warning).
        					setMessage(R.string.amount_too_big).
        					setNegativeButton(R.string.back, new DialogInterface.OnClickListener(){
								public void onClick(DialogInterface dialog,
										int which) {
									
								}
        					}).
        					setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
								public void onClick(DialogInterface dialog,
										int which) {
									if ( mode == MODE_EDIT_ITEM )
				        				MenuManager.getInstance(getApplicationContext()).
				        						updateMenuItem(menuItemId,weightItemId,amount);
				        			else
				        				MenuManager.getInstance(getApplicationContext()).
												saveNewMenuItem(prodId,weightItemId,amount);
									setResult(RESULT_OK);
									finish();
								}
        					}).show();
        		}	
        	}
        });
        picturesButton.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View v){
        		Intent intent = new Intent(getApplicationContext(), ProductPictureActivity.class);
//        		Log.v("prodinfo", "prodid = "+prodId);
        		intent.putExtra(ProductPictureActivity.INTENT_EXTRA_NAME, prodId);
        		startActivity(intent);
        	}
        });
        
	}
	
	private void checkAmount(){
		int curProtValue, curFatValue, curCarboValue;
		weightItemId = (int)weightSpinner.getSelectedItemId();
		if(TextUtils.isEmpty(amountEditText.getText().toString()))
			amount = 0;
		else
			amount = Integer.parseInt(amountEditText.getText().toString());
		if (ProductDataManager.getInstance(getApplicationContext()).
				isAcceptable(prodId, weightItemId, amount)){
			amountEditText.setBackgroundResource(R.drawable.textfield_green);
			amountIsOk = true;
		}
		else{
			amountEditText.setBackgroundResource(R.drawable.textfield_red);
			amountIsOk = false;
		}
		weight = Math.round(ProductDataManager.getInstance(getApplicationContext()).
					countWeight(weightItemId, amount));
		StringBuffer sbuf = new StringBuffer(getString(R.string.per));
		sbuf.append(' ').append(amount).append(" x ").append(ProductDataManager.
				getInstance(getApplicationContext()).getWeightItemNameById(weightItemId)).
				append(" (").append(weight).append(' ').
				append(getString(R.string.g)).append(')');
		
		perAmountTitle.setText(sbuf.toString());
		
		curProtEnergy = Math.round(ProductDataManager.getInstance(getApplicationContext()).
				getProductProtEnergy(prodId)* weight / ProductDataManager.STANDARD_WEIGHT );
		curProtValue = Math.round(ProductDataManager.getInstance(getApplicationContext()).
				getProductProtValue(prodId)* weight / ProductDataManager.STANDARD_WEIGHT );
		curFatEnergy = Math.round(ProductDataManager.getInstance(getApplicationContext()).
				getProductFatEnergy(prodId)* weight / ProductDataManager.STANDARD_WEIGHT );
		curFatValue = Math.round(ProductDataManager.getInstance(getApplicationContext()).
				getProductFatValue(prodId)* weight / ProductDataManager.STANDARD_WEIGHT );
		curCarboEnergy = Math.round(ProductDataManager.getInstance(getApplicationContext()).
				getProductCarboEnergy(prodId)* weight / ProductDataManager.STANDARD_WEIGHT );
		curCarboValue = Math.round(ProductDataManager.getInstance(getApplicationContext()).
				getProductCarboValue(prodId)* weight / ProductDataManager.STANDARD_WEIGHT );
		curEnergy = Math.round(ProductDataManager.getInstance(getApplicationContext()).
				getProductEnergyValue(prodId)* weight / ProductDataManager.STANDARD_WEIGHT );
		
		sbuf = new StringBuffer();
		sbuf.append(curProtValue).append(' ').append(getString(R.string.g)).
				append(" (").append(curProtEnergy).append(' ').append(getString(R.string.kcal)).
				append(')');
		perAmountProt.setText(sbuf.toString());
		
		sbuf = new StringBuffer();
		sbuf.append(curFatValue).append(' ').append(getString(R.string.g)).
				append(" (").append(curFatEnergy).append(' ').append(getString(R.string.kcal)).
				append(')');
		perAmountFat.setText(sbuf.toString());
		
		sbuf = new StringBuffer();
		sbuf.append(curCarboValue).append(' ').append(getString(R.string.g)).
				append(" (").append(curCarboEnergy).append(' ').append(getString(R.string.kcal)).
				append(')');
		perAmountCarbo.setText(sbuf.toString());
		
		sbuf = new StringBuffer();
		sbuf.append(curEnergy).append(' ').append(getString(R.string.kcal));
		perAmountEnergy.setText(sbuf.toString());
	}
	
	private class ServingAdapter extends SimpleCursorAdapter{

		public ServingAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView text;
//			ViewGroup v;
			if (convertView != null)
//				v = (ViewGroup)convertView;
				text = (TextView)convertView;
			else
				text = (TextView)LayoutInflater.from(getApplicationContext()).
						inflate(android.R.layout.simple_spinner_item, null);
			int id = getIdByPosition(getCursor(), position);
			text.setText(ProductDataManager.getInstance(getApplicationContext()).
					getWeightItemNameById(id));
			return text;	
		}
		
		private int getIdByPosition(Cursor c, int pos){
			c.moveToPosition(pos);
			return c.getInt( c.getColumnIndex(MenuProvider.COLUMN_NAMES[MenuProvider.ID]) );
		}		
	}
	
}

